package com.flw.dao.impl;

import com.flw.dao.IScheduleDao;
import com.flw.entity.Cinema;
import com.flw.entity.Movie;
import com.flw.entity.Schedule;
import com.hbm.util.DateUtil;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.transaction.Transactional;
import java.util.Date;
import java.util.List;

/**
 * 本类用于：
 *
 * @author Bruce
 * @date 2017/7/23 21:02
 */
@SuppressWarnings("all")
@Repository
@Transactional
public class ScheduleDaoImpl implements IScheduleDao{

    @Autowired
    private SessionFactory sessionFactory;

    public Session getSession(){
        return this.sessionFactory.getCurrentSession();
    }

    @Override
    public void save(Schedule schedule) {
        getSession().save(schedule);
    }

    @Override
    public void delete(Long schId) {
        Schedule schedule = (Schedule) getSession().get(Schedule.class, schId);
        if(schedule != null){
            getSession().delete(schedule);
        }
    }

    @Override
    public void update(Schedule schedule) {
        Schedule s = (Schedule) getSession().get(Schedule.class, schedule.getSchId());
        if(s != null){
            getSession().clear();
            getSession().update(schedule);
        }
    }

    @Override
    public Schedule findById(Long schId) {
        return (Schedule) getSession().get(Schedule.class, schId);
    }

    @Override
    public List<Schedule> findByConditions(Movie movie, Date schDate, Cinema cinema) {

        //定义一个hql语句
        String hql = "from Schedule where 1=1";

        if(null != movie){
            hql += " and movie ="+movie.getId();
        }

        if(null != schDate){
            //将java.util.Date 时间转换成sql的TimeStamp时间
            java.sql.Timestamp dt = new java.sql.Timestamp(schDate.getTime());
            hql += " and to_char(schDate)>='"+dt+"'";
        }

        if(null != cinema){
            hql += " and cinema="+cinema.getId();
        }

        //定义一个查询返回变量
        Query query = getSession().createQuery(hql);

        return query.list();
    }
}
